Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Renew golden token indexing #279

Merged
merged 5 commits into from
Oct 7, 2024
Merged

Renew golden token indexing #279

merged 5 commits into from
Oct 7, 2024

Conversation

starknetdev
Copy link
Member

@starknetdev starknetdev commented Oct 7, 2024

Instead of the old realms world indexing infra we are now using blast apis development api.

Summary by CodeRabbit

  • New Features

    • Introduced a function to fetch golden tokens associated with a wallet address.
    • Added state management for golden tokens in the main component.
  • Changes to Existing Features

    • Updated components to use the new goldenTokens property instead of removed properties.
    • Streamlined token fetching process by removing outdated implementations.
  • Bug Fixes

    • Fixed issues related to the handling of token data across various components.
  • Chores

    • Cleaned up unused variables and imports for improved code clarity.

- remove realms apollo client context
- add blastapi nftcollection query
- fix dependencies for golden tokens fetch
Copy link

vercel bot commented Oct 7, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
loot-survivor ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 7, 2024 6:48pm

Copy link

coderabbitai bot commented Oct 7, 2024

Warning

Rate limit exceeded

@starknetdev has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 8 minutes and 20 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Files that changed from the base of the PR and between d79b900 and def8051.

Walkthrough

This pull request introduces a new asynchronous function getGoldenTokens to fetch golden tokens linked to a wallet address from a blockchain network. It updates several components (CreateAdventurer, Spawn, AdventurerScreen) to replace old properties with a new required property goldenTokens, which is an array of numbers. The useCustomQuery hook and the RootLayout component have also been adjusted for improved structure and functionality. Additionally, the networkConfig has been modified to include a blastUrl for network interactions, and the main page now integrates the new token fetching functionality.

Changes

File Path Change Summary
ui/src/app/api/getGoldenTokens.ts Added asynchronous function getGoldenTokens(owner: string, goldenTokenAddress: string, network: Network).
ui/src/app/components/start/CreateAdventurer.tsx Updated CreateAdventurerProps interface: removed lordsBalance, goldenTokenData; added goldenTokens: number[]. Adjusted component logic accordingly.
ui/src/app/components/start/Spawn.tsx Updated SpawnProps interface: removed lordsBalance, goldenTokenData; added goldenTokens: number[]. Simplified logic for obtaining usable golden tokens.
ui/src/app/containers/AdventurerScreen.tsx Updated AdventurerScreenProps interface: removed lordsBalance, replaced goldenTokenData with goldenTokens: number[]. Adjusted component logic accordingly.
ui/src/app/hooks/useCustomQuery.ts Rearranged imports, removed gameClient and networkConfig, eliminated memoization of Apollo Client instance.
ui/src/app/layout.tsx Reorganized imports, adjusted ApolloProvider structure, and streamlined conditional rendering logic.
ui/src/app/lib/networkConfig.ts Added blastUrl to configurations for sepolia, mainnet, katana, and localKatana; removed tokensGQLURL from sepolia and mainnet.
ui/src/app/page.tsx Added handleFetchGoldenTokens function and goldenTokens state; updated props passed to AdventurerScreen.

Possibly related PRs

  • Payment QOL #273: The changes in Spawn.tsx regarding the handling of golden tokens and payment processes are directly related to the new getGoldenTokens function introduced in the main PR, as both involve the management and utilization of golden tokens within the application.

🐰 In a world of tokens, shiny and bright,
I hop through the code, with joy and delight.
New functions and props, all gleaming and new,
Fetching golden treasures, just for me and you!
So let's dance through the branches, with code that's refined,
A rabbit's adventure, in the world of the kind! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

🧹 Outside diff range and nitpick comments (11)
ui/src/app/hooks/useCustomQuery.ts (2)

Line range hint 24-27: LGTM! Consider adding a clarifying comment.

The removal of the client option from the useQuery call is consistent with the changes in imports. The hook now uses the default Apollo Client instance.

Consider adding a comment to explain the use of the default Apollo Client:

 const { data, refetch } = useQuery(query, {
   variables: variables,
   skip: skip,
+  // Using the default Apollo Client instance
 });

Line range hint 1-43: Summary: Simplified Apollo Client usage in custom hook.

The changes in this file streamline the useCustomQuery hook by removing the custom Apollo Client creation. This modification is likely part of a larger refactoring effort to centralize Apollo Client configuration, which should improve maintainability and consistency across the application.

Key points:

  1. Removed custom Apollo Client creation
  2. Now using the default Apollo Client instance
  3. Overall hook functionality remains unchanged

These changes appear to be an improvement in the code structure. However, ensure that the global Apollo Client setup is properly configured to handle different networks as needed by this hook.

Consider documenting the new Apollo Client setup in the project's README or a separate GraphQL documentation file to help other developers understand the centralized configuration approach.

ui/src/app/components/start/CreateAdventurer.tsx (2)

12-12: LGTM! Consider updating documentation.

The changes to the CreateAdventurerProps interface look good. The new goldenTokens property replaces the previous lordsBalance and goldenTokenData, which seems to be a more straightforward approach to handling golden token data.

Consider updating any relevant documentation or comments to reflect these changes, especially regarding the removal of mintLords functionality and the new structure of golden token data.


Line range hint 1-150: Overall changes look good. Consider broader impact analysis.

The modifications to the CreateAdventurer component and its related interfaces improve the handling of golden token data by introducing a more straightforward goldenTokens prop. The changes are consistent throughout the file.

Consider conducting a broader impact analysis to ensure that:

  1. The removal of mintLords functionality doesn't negatively impact other parts of the application.
  2. Any components or utilities that previously relied on lordsBalance or goldenTokenData have been updated accordingly.
  3. The new goldenTokens data structure is compatible with the rest of the application's state management and API interactions.

This will help maintain the overall consistency and functionality of the application.

ui/src/app/containers/AdventurerScreen.tsx (1)

28-28: Improved type safety for goldenTokens

The change from goldenTokenData: any; to goldenTokens: number[]; enhances type safety and clarity. This is a positive improvement.

Consider adding a brief comment explaining the purpose of goldenTokens for better code documentation:

/** Array of golden token IDs associated with the adventurer */
goldenTokens: number[];
ui/src/app/components/start/Spawn.tsx (3)

44-48: Approved: Updated prop destructuring in Spawn component

The changes to the prop destructuring in the Spawn component correctly reflect the updates made to the SpawnProps interface. The removal of lordsBalance and goldenTokenData, and the addition of goldenTokens align with the new data structure for golden tokens.

Consider renaming goldenTokens to something more specific, such as goldenTokenIds, to clearly indicate that it's an array of token IDs. This would improve code readability and make the purpose of the prop more explicit.

-  goldenTokens,
+  goldenTokenIds,

127-127: Approved: Updated getUsableGoldenToken function call

The change to use goldenTokens ?? [] in the getUsableGoldenToken function call is a good improvement. It simplifies the token retrieval process and aligns with the new data structure while providing a fallback empty array to prevent potential errors.

Consider adding a console warning or error logging when goldenTokens is undefined, as this might indicate an unexpected state in the application:

-    getUsableGoldenToken(goldenTokens ?? []);
+    if (goldenTokens === undefined) {
+      console.warn('goldenTokens is undefined in Spawn component');
+    }
+    getUsableGoldenToken(goldenTokens ?? []);

This addition would help with debugging and identifying potential issues in the data flow.


⚠️ Incomplete Refactoring of Golden Token Handling

The refactoring to replace goldenTokenData with goldenTokens in the Spawn component has been partially successful. While Spawn.tsx no longer references goldenTokenData, there are still instances of goldenTokenData in ui/src/app/api/getGoldenTokens.ts. Additionally, goldenTokens is correctly used in multiple files, including Spawn.tsx, page.tsx, CreateAdventurer.tsx, and AdventurerScreen.tsx.

Action Items:

  • Update getGoldenTokens.ts:

    • Remove or replace goldenTokenData with goldenTokens.
    • Ensure that the data fetching and handling logic aligns with the new structure.
  • Verify Consistency Across the Codebase:

    • Ensure no other files reference goldenTokenData.
    • Update any related unit tests to reflect these changes.
🔗 Analysis chain

Line range hint 1-438: Summary: Successful refactoring of golden token handling

The changes made to the Spawn component successfully refactor the handling of golden tokens. The modifications are well-contained and focused on the specific areas that needed updating. The transition from using goldenTokenData to a simpler goldenTokens array appears to be seamless and doesn't disrupt the overall functionality of the component.

These changes should improve the component's maintainability and type safety. However, to ensure the refactoring hasn't introduced any regressions, consider the following:

  1. Update any unit tests associated with this component to reflect the new prop structure.
  2. Perform thorough manual testing of the golden token functionality to verify it works as expected with the new data structure.
  3. Review any parent components or contexts that provide the golden token data to ensure they're now passing an array of numbers instead of the previous data structure.

To help with this verification, you can run the following script to check for any remaining references to the old data structure:

This will help ensure that the refactoring has been applied consistently across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining usage of goldenTokenData in the codebase

echo "Checking for goldenTokenData usage:"
rg --type typescript 'goldenTokenData'

echo "Checking for new goldenTokens usage:"
rg --type typescript 'goldenTokens'

Length of output: 308


Script:

#!/bin/bash
# Description: Recheck for any remaining usage of goldenTokenData in the codebase with corrected file type

echo "Rechecking for goldenTokenData usage:"
rg --type tsx 'goldenTokenData'

echo "Rechecking for new goldenTokens usage:"
rg --type tsx 'goldenTokens'

Length of output: 288


Script:

#!/bin/bash
# Description: Recheck for any remaining usage of goldenTokenData and verify new goldenTokens usage in .ts and .tsx files

echo "Rechecking for goldenTokenData usage in .ts files:"
rg --glob '*.ts' 'goldenTokenData'

echo "Rechecking for goldenTokenData usage in .tsx files:"
rg --glob '*.tsx' 'goldenTokenData'

echo "Rechecking for new goldenTokens usage in .ts files:"
rg --glob '*.ts' 'goldenTokens'

echo "Rechecking for new goldenTokens usage in .tsx files:"
rg --glob '*.tsx' 'goldenTokens'

Length of output: 2038

ui/src/app/page.tsx (2)

97-97: Golden tokens state and fetching logic added.

The implementation for fetching and storing golden tokens is well-structured. The state is correctly initialized, and the useEffect hook ensures that the tokens are fetched when necessary.

However, consider adding error handling to the handleFetchGoldenTokens function:

 const handleFetchGoldenTokens = async () => {
+  try {
     const goldenTokens = await getGoldenTokens(
       address ?? "",
       networkConfig[network!].goldenTokenAddress,
       network
     );
     setGoldenTokens(goldenTokens);
+  } catch (error) {
+    console.error("Failed to fetch golden tokens:", error);
+    // Optionally, update UI to show error state
+  }
 };

This will ensure that any errors during the fetch process are properly logged and handled.

Also applies to: 470-481


882-882: Golden tokens prop added to AdventurerScreen component.

The goldenTokens state is correctly passed as a prop to the AdventurerScreen component, allowing it to access and display the golden tokens data.

For improved type safety, consider adding a prop type for goldenTokens in the AdventurerScreen component:

interface AdventurerScreenProps {
  // ... other props
  goldenTokens: number[];
}

This will ensure that the correct type of data is always passed to the component.

ui/src/app/api/getGoldenTokens.ts (1)

24-26: Remove unnecessary Content-Type header for GET request

The Content-Type header is typically used to indicate the media type of the request body in POST or PUT requests. It is unnecessary for a GET request with no body. Consider removing it.

Apply this diff to remove the unnecessary header:

const response = await fetch(url, {
  method: "GET",
-  headers: {
-    "Content-Type": "application/json",
-  },
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3bf7608 and f7a9072.

📒 Files selected for processing (8)
  • ui/src/app/api/getGoldenTokens.ts (1 hunks)
  • ui/src/app/components/start/CreateAdventurer.tsx (3 hunks)
  • ui/src/app/components/start/Spawn.tsx (3 hunks)
  • ui/src/app/containers/AdventurerScreen.tsx (3 hunks)
  • ui/src/app/hooks/useCustomQuery.ts (1 hunks)
  • ui/src/app/layout.tsx (2 hunks)
  • ui/src/app/lib/networkConfig.ts (4 hunks)
  • ui/src/app/page.tsx (5 hunks)
🧰 Additional context used
🔇 Additional comments (13)
ui/src/app/hooks/useCustomQuery.ts (1)

1-4: LGTM! Verify global Apollo Client setup.

The changes to the import statements look good. The removal of gameClient and networkConfig imports suggests a shift towards using a global Apollo Client instance.

Please confirm that a global Apollo Client instance is properly set up elsewhere in the application. Run the following script to verify:

✅ Verification successful

Verified: Global Apollo Client is correctly set up.
The global Apollo Client instance is properly initialized in ui/src/app/lib/clients.ts. No further action is required.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for Apollo Client setup in the application

# Test: Search for Apollo Client setup
rg --type typescript -e "new ApolloClient" -e "createClient" -e "makeApolloClient"

Length of output: 115


Script:

#!/bin/bash
# Description: Check for Apollo Client setup in the application

# Test: Search for Apollo Client setup in TypeScript files
rg -g "*.ts" -g "*.tsx" -e "new ApolloClient" -e "createClient" -e "makeApolloClient"

Length of output: 191

ui/src/app/components/start/CreateAdventurer.tsx (2)

23-23: LGTM! Props updated correctly.

The changes to the destructured props in the CreateAdventurer component correctly reflect the updates made to the CreateAdventurerProps interface. The addition of goldenTokens and the removal of lordsBalance, goldenTokenData, and mintLords are consistent with the new data structure.


118-122: LGTM! Verify Spawn component implementation.

The updates to the Spawn component props are consistent with the changes made to the CreateAdventurer component and its interface. Both instances of the Spawn component have been updated correctly.

Please ensure that the Spawn component has been updated to handle the new goldenTokens prop correctly and that it no longer relies on the removed lordsBalance, goldenTokenData, and mintLords props. Run the following script to verify the Spawn component implementation:

Also applies to: 142-146

✅ Verification successful

Please run the following shell scripts to verify the Spawn component implementation:


Verified! The Spawn component correctly uses the goldenTokens prop and no longer relies on lordsBalance, goldenTokenData, or mintLords.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify Spawn component implementation

# Test: Check if Spawn component is using goldenTokens prop and not using removed props
ast-grep --lang typescript --pattern $'function Spawn({ $$$, goldenTokens, $$$ }: SpawnProps) {
  $$$
}'

# Test: Ensure lordsBalance, goldenTokenData, and mintLords are not used in Spawn
rg --type typescript 'lordsBalance|goldenTokenData|mintLords' $(fd -e tsx -e ts)

Length of output: 8325


Script:

#!/bin/bash
# Description: Verify Spawn component implementation

# Test: Check if Spawn component is using goldenTokens prop and matches the expected pattern
ast-grep --lang typescript --pattern $'function Spawn({ $$$, goldenTokens, $$$ }: SpawnProps) {
  $$$
}'

# Test: Ensure lordsBalance, goldenTokenData, and mintLords are not used in Spawn
rg 'lordsBalance|goldenTokenData|mintLords' -- '*.ts' '*.tsx'

Length of output: 260


Script:

#!/bin/bash
# Description: Verify Spawn component implementation

# Test: Check if Spawn component is using goldenTokens prop and matches the expected pattern
ast-grep --lang typescript --pattern $'const Spawn = ({ $$$, goldenTokens, $$$ }: SpawnProps) => {
  $$$
}'

# Test: Ensure lordsBalance, goldenTokenData, and mintLords are not used in Spawn
rg 'lordsBalance|goldenTokenData|mintLords' --glob='*.ts' --glob='*.tsx'

Length of output: 3817

ui/src/app/containers/AdventurerScreen.tsx (2)

48-48: Props updated to match interface changes

The addition of goldenTokens to the destructured props aligns with the interface changes. This is correct and maintains consistency.

To ensure all necessary changes have been made, please verify the removal of lordsBalance and mintLords from the props. Run the following script to check for any remaining references:

✅ Verification successful

Removed lordsBalance and mintLords props properly

No remaining references to lordsBalance and mintLords were found in AdventurerScreen.tsx. The props have been successfully removed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to removed props

# Test: Search for lordsBalance and mintLords in the file
rg --type typescript 'lordsBalance|mintLords' ui/src/app/containers/AdventurerScreen.tsx

Length of output: 125


Script:

#!/bin/bash
# Description: Check for any remaining references to removed props

# Test: Search for lordsBalance and mintLords in the file
rg --type tsx 'lordsBalance|mintLords' ui/src/app/containers/AdventurerScreen.tsx

Length of output: 111


Script:

#!/bin/bash
# Description: Check for any remaining references to removed props

# Test: Search for lordsBalance and mintLords in the file without specifying file type
rg 'lordsBalance|mintLords' ui/src/app/containers/AdventurerScreen.tsx

Length of output: 72


136-140: Props correctly passed to CreateAdventurer

The goldenTokens prop is now correctly passed to the CreateAdventurer component, aligning with the interface changes. This ensures that the child component receives the updated data structure.

To ensure the CreateAdventurer component is using the new goldenTokens prop correctly and has removed any references to the old goldenTokenData, lordsBalance, and mintLords props, run the following script:

Ensure that the CreateAdventurer component's props and implementation have been updated to match these changes.

ui/src/app/lib/networkConfig.ts (5)

78-78: Clarify the empty blastUrl for katana configuration

The blastUrl property has been added to the katana configuration, but it's set to an empty string. Could you please clarify:

  1. Is this intentional, or should there be a specific URL for the katana environment?
  2. If intentional, are there any plans to implement Blast API support for katana in the future?

This information will help ensure consistency across different environments and prevent potential issues in the future.


107-107: Clarify the empty blastUrl for localKatana configuration

Similar to the katana configuration, the blastUrl property for localKatana is set to an empty string. Please provide clarification on this:

  1. Is this intentional for the local development environment?
  2. If so, how should the application behave when encountering an empty blastUrl?
  3. Are there any specific considerations or setup steps for local development regarding the Blast API integration?

This information will help ensure smooth local development and testing processes.


Line range hint 1-135: Summary of networkConfig.ts changes

The changes in this file align with the PR objective of transitioning to Blast APIs for golden token indexing. Here's a summary of the key points:

  1. blastUrl has been added to all environment configurations.
  2. The sepolia configuration uses a mainnet URL, which needs verification.
  3. The katana and localKatana configurations have empty blastUrl values, requiring clarification.
  4. The removal of tokensGQLURL is not visible in the diff but is mentioned in the summary and needs confirmation.

Please address the points raised in the individual comments to ensure consistency and clarity across all environment configurations.

#!/bin/bash
# Verify the presence and usage of blastUrl and tokensGQLURL
echo "Occurrences of blastUrl:"
grep -n "blastUrl" ui/src/app/lib/networkConfig.ts

echo "\nOccurrences of tokensGQLURL:"
grep -n "tokensGQLURL" ui/src/app/lib/networkConfig.ts

echo "\nCheck for any TODO comments related to these changes:"
grep -n "TODO" ui/src/app/lib/networkConfig.ts

6-7: Verify the blastUrl for sepolia configuration

The blastUrl has been added, which aligns with the PR objective of transitioning to Blast APIs. However, the URL appears to be for the mainnet environment, not sepolia. Please verify if this is intentional or if it should be updated to a sepolia-specific endpoint.

Also, confirm if the removal of tokensGQLURL (not visible in this diff) is intentional and consistent with the new API usage.


39-40: LGTM! Verify removal of tokensGQLURL

The addition of blastUrl for the mainnet configuration is correct and aligns with the PR objectives. The URL is appropriate for the mainnet environment.

Please confirm that the tokensGQLURL property has been removed from this configuration as well, as it's not visible in this diff but mentioned in the summary.

✅ Verification successful

Verified! The tokensGQLURL property has been successfully removed from the mainnet configuration.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify if tokensGQLURL has been removed from mainnet config
grep -n "tokensGQLURL" ui/src/app/lib/networkConfig.ts

Length of output: 479

ui/src/app/page.tsx (2)

7-7: New import for golden tokens functionality added.

The getGoldenTokens function is now imported from the API, which is a good practice for modularizing the code and separating concerns.


Line range hint 1-938: Golden tokens feature successfully integrated.

The changes to integrate the golden tokens functionality are well-implemented. The code maintains good structure and follows React best practices. The new feature is properly integrated with existing state management and component structure.

Key points:

  1. New import for getGoldenTokens function.
  2. State management for golden tokens with proper fetching logic.
  3. Integration with the AdventurerScreen component.

The suggestions for error handling and type safety will further improve the robustness of the implementation. Overall, this is a solid addition to the main page component.

ui/src/app/layout.tsx (1)

86-90: Verify the Nesting Order of Context Providers

The context providers are nested as follows:

<ApolloProvider client={gameClient(networkConfig[network].lsGQLURL!)}>
  <ControllerProvider>
    <StarknetProvider network={network}>
      <DojoProvider value={setupResult}>{children}</DojoProvider>
    </StarknetProvider>
  </ControllerProvider>
</ApolloProvider>

Ensure that the order of these providers aligns with their dependencies. If ControllerProvider depends on StarknetProvider or any other provider, nesting them incorrectly could lead to context issues within child components.

To verify, check if any context consumers inside ControllerProvider require the contexts provided by StarknetProvider or DojoProvider. If so, adjust the nesting order accordingly:

<ApolloProvider client={gameClient(networkConfig[network].lsGQLURL!)}>
  <StarknetProvider network={network}>
    <ControllerProvider>
      <DojoProvider value={setupResult}>{children}</DojoProvider>
    </ControllerProvider>
  </StarknetProvider>
</ApolloProvider>

@@ -13,7 +13,7 @@ import useUIStore from "@/app/hooks/useUIStore";
import { battle } from "@/app/lib/constants";
import { networkConfig } from "@/app/lib/networkConfig";
import { formatLords } from "@/app/lib/utils";
import { Adventurer, FormData, GameToken } from "@/app/types";
import { Adventurer, FormData } from "@/app/types";
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Action Required: Remaining References to lordsBalance and goldenTokenData Detected

The following files still reference lordsBalance and goldenTokenData, which need to be updated to align with the recent SpawnProps modifications:

  • lordsBalance:

    • ui/src/app/page.tsx
    • ui/src/app/lib/utils/syscalls.ts
    • ui/src/app/lib/balances.ts
    • ui/src/app/containers/TopUp.tsx
    • ui/src/app/containers/Onboarding.tsx
    • ui/src/app/components/profile/ProfileDialog.tsx
    • ui/src/app/components/navigation/Header.tsx
  • goldenTokenData:

    • ui/src/app/api/getGoldenTokens.ts
  • goldenTokens:

    • ui/src/app/page.tsx
    • ui/src/app/containers/AdventurerScreen.tsx
    • ui/src/app/components/start/CreateAdventurer.tsx
    • ui/src/app/components/start/Spawn.tsx

Please update these references to ensure consistency and type safety across the codebase.

🔗 Analysis chain

Approved: Updated imports and SpawnProps interface

The changes to the imports and SpawnProps interface look good. The addition of Adventurer and FormData types import suggests improved type safety. The modification of SpawnProps to use goldenTokens: number[] instead of goldenTokenData: any is a positive change, as it provides more specific typing and potentially simplifies the component's logic.

To ensure this change is consistently applied throughout the codebase, please run the following script:

Also applies to: 33-37

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining usage of lordsBalance or goldenTokenData in SpawnProps

# Search for lordsBalance in SpawnProps
echo "Checking for lordsBalance in SpawnProps:"
rg --type typescript 'SpawnProps.*lordsBalance'

# Search for goldenTokenData in SpawnProps
echo "Checking for goldenTokenData in SpawnProps:"
rg --type typescript 'SpawnProps.*goldenTokenData'

# Search for usage of goldenTokens in SpawnProps
echo "Checking for goldenTokens in SpawnProps:"
rg --type typescript 'SpawnProps.*goldenTokens'

Length of output: 536


Script:

#!/bin/bash
# Description: Check for any remaining usage of lordsBalance or goldenTokenData in SpawnProps

# Define the search patterns
PATTERNS=("lordsBalance" "goldenTokenData")

# Iterate over each pattern and search in .ts and .tsx files
for pattern in "${PATTERNS[@]}"; do
  echo "Checking for ${pattern} in SpawnProps:"
  rg "${pattern}" --glob "*.ts" --glob "*.tsx"
done

# Additionally, check for usage of goldenTokens in SpawnProps
echo "Checking for goldenTokens in SpawnProps:"
rg "goldenTokens" --glob "*.ts" --glob "*.tsx"

Length of output: 3865

Comment on lines 13 to 15
let url = `${
networkConfig[network!].blastUrl
}/builder/getWalletNFTs?contractAddress=${goldenTokenAddress}&walletAddress=${owner}&pageSize=100`;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid using non-null assertion operator; ensure network is defined

Using the non-null assertion operator (!) can mask potential null or undefined errors. Instead, consider adding a runtime check to ensure that network is defined or handle cases where it might be undefined.

Apply this diff to add a check:

+ if (!network) {
+   throw new Error("Network is not defined");
+ }
let url = `${
-   networkConfig[network!].blastUrl
+   networkConfig[network].blastUrl
}/builder/getWalletNFTs?contractAddress=...`;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let url = `${
networkConfig[network!].blastUrl
}/builder/getWalletNFTs?contractAddress=${goldenTokenAddress}&walletAddress=${owner}&pageSize=100`;
if (!network) {
throw new Error("Network is not defined");
}
let url = `${
networkConfig[network].blastUrl
}/builder/getWalletNFTs?contractAddress=${goldenTokenAddress}&walletAddress=${owner}&pageSize=100`;

⚠️ Potential issue

URL-encode query parameters to prevent injection attacks

Directly interpolating user-provided values into a URL can lead to injection vulnerabilities. Use encodeURIComponent to safely encode goldenTokenAddress and owner parameters.

Apply this diff to encode the parameters:

let url = `${
  networkConfig[network!].blastUrl
}/builder/getWalletNFTs?contractAddress=${
-   goldenTokenAddress
+   encodeURIComponent(goldenTokenAddress)
}&walletAddress=${
-   owner
+   encodeURIComponent(owner)
}&pageSize=100`;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let url = `${
networkConfig[network!].blastUrl
}/builder/getWalletNFTs?contractAddress=${goldenTokenAddress}&walletAddress=${owner}&pageSize=100`;
let url = `${
networkConfig[network!].blastUrl
}/builder/getWalletNFTs?contractAddress=${
encodeURIComponent(goldenTokenAddress)
}&walletAddress=${
encodeURIComponent(owner)
}&pageSize=100`;

Comment on lines +9 to +12
const recursiveFetch: any = async (
goldenTokens: any[],
nextPageKey: string | null
) => {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Specify explicit types instead of using any

Using any defeats TypeScript's static type checking. Consider defining explicit types for the recursiveFetch function and its parameters to enhance type safety and maintainability.

Apply this diff to specify explicit types:

- const recursiveFetch: any = async (
-   goldenTokens: any[],
-   nextPageKey: string | null
- ) => {
+ const recursiveFetch = async (
+   goldenTokens: number[],
+   nextPageKey: string | null
+ ): Promise<number[]> => {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const recursiveFetch: any = async (
goldenTokens: any[],
nextPageKey: string | null
) => {
const recursiveFetch = async (
goldenTokens: number[],
nextPageKey: string | null
): Promise<number[]> => {

Comment on lines +29 to +35
const data = await response.json();
goldenTokens = goldenTokens.concat(
data?.nfts?.map((goldenToken: any) => {
const tokenId = JSON.parse(goldenToken.tokenId);
return Number(tokenId);
})
);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Handle cases where data.nfts might be undefined

If data.nfts is undefined or null, mapping over it will result in an error. Consider adding a check to ensure data.nfts is an array before mapping over it.

Apply this diff to add a default empty array if data.nfts is undefined:

const data = await response.json();
goldenTokens = goldenTokens.concat(
-   data?.nfts?.map((goldenToken: any) => {
+   (data?.nfts ?? []).map((goldenToken: any) => {
      const tokenId = Number(goldenToken.tokenId);
      return tokenId;
    })
);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const data = await response.json();
goldenTokens = goldenTokens.concat(
data?.nfts?.map((goldenToken: any) => {
const tokenId = JSON.parse(goldenToken.tokenId);
return Number(tokenId);
})
);
const data = await response.json();
goldenTokens = goldenTokens.concat(
(data?.nfts ?? []).map((goldenToken: any) => {
const tokenId = JSON.parse(goldenToken.tokenId);
return Number(tokenId);
})
);

Comment on lines +31 to +34
data?.nfts?.map((goldenToken: any) => {
const tokenId = JSON.parse(goldenToken.tokenId);
return Number(tokenId);
})
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid unnecessary JSON.parse on goldenToken.tokenId

Using JSON.parse on goldenToken.tokenId may be unnecessary and could lead to errors if tokenId is not valid JSON. If goldenToken.tokenId is a string representation of a number, you can convert it directly using Number(goldenToken.tokenId).

Apply this diff to simplify the code:

const data = await response.json();
goldenTokens = goldenTokens.concat(
  (data?.nfts ?? []).map((goldenToken: any) => {
-    const tokenId = JSON.parse(goldenToken.tokenId);
+    const tokenId = Number(goldenToken.tokenId);
     return tokenId;
  })
);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
data?.nfts?.map((goldenToken: any) => {
const tokenId = JSON.parse(goldenToken.tokenId);
return Number(tokenId);
})
data?.nfts?.map((goldenToken: any) => {
const tokenId = Number(goldenToken.tokenId);
return tokenId;
})

Comment on lines +22 to +29
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});

const data = await response.json();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add response status check before parsing JSON

Currently, the code assumes that the fetch request is successful and proceeds to parse the response JSON. To handle potential HTTP errors, check response.ok and handle error statuses appropriately before calling response.json().

Apply this diff to add a response status check:

try {
  const response = await fetch(url, {
    method: "GET",
    // headers...
  });

+  if (!response.ok) {
+    throw new Error(`HTTP error! Status: ${response.status}`);
+  }

  const data = await response.json();
  // Process data...

Committable suggestion was skipped due to low confidence.

Comment on lines 9 to 45
const recursiveFetch: any = async (
goldenTokens: any[],
nextPageKey: string | null
) => {
let url = `${
networkConfig[network!].blastUrl
}/builder/getWalletNFTs?contractAddress=${goldenTokenAddress}&walletAddress=${owner}&pageSize=100`;

if (nextPageKey) {
url += `&pageKey=${nextPageKey}`;
}

try {
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});

const data = await response.json();
goldenTokens = goldenTokens.concat(
data?.nfts?.map((goldenToken: any) => {
const tokenId = JSON.parse(goldenToken.tokenId);
return Number(tokenId);
})
);

if (data.nextPageKey) {
return recursiveFetch(goldenTokens, data.nextPageKey);
}
} catch (ex) {
console.log("error fetching golden tokens", ex);
}

return goldenTokens;
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Refactor recursion to iteration for fetching data

Using recursion for fetching paginated data can lead to stack overflow errors if the number of pages is large. An iterative approach is more reliable and efficient.

Apply this diff to refactor to an iterative approach:

- const recursiveFetch = async (
-   goldenTokens: number[],
-   nextPageKey: string | null
- ): Promise<number[]> => {
-   // Recursive fetching logic...
- };
-
- let goldenTokenData = await recursiveFetch([], null);

+ const fetchAllPages = async (): Promise<number[]> => {
+   let goldenTokens: number[] = [];
+   let nextPageKey: string | null = null;
+   do {
+     let url = `${
+       networkConfig[network].blastUrl
+     }/builder/getWalletNFTs?contractAddress=${encodeURIComponent(goldenTokenAddress)}&walletAddress=${encodeURIComponent(owner)}&pageSize=100`;
+     if (nextPageKey) {
+       url += `&pageKey=${nextPageKey}`;
+     }
+     try {
+       const response = await fetch(url, {
+         method: "GET",
+       });
+       if (!response.ok) {
+         throw new Error(`HTTP error! Status: ${response.status}`);
+       }
+       const data = await response.json();
+       goldenTokens = goldenTokens.concat(
+         (data?.nfts ?? []).map((goldenToken: any) => {
+           const tokenId = Number(goldenToken.tokenId);
+           return tokenId;
+         })
+       );
+       nextPageKey = data.nextPageKey || null;
+     } catch (ex) {
+       console.log("error fetching golden tokens", ex);
+       break;
+     }
+   } while (nextPageKey);
+   return goldenTokens;
+ };
+
+ let goldenTokenData = await fetchAllPages();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const recursiveFetch: any = async (
goldenTokens: any[],
nextPageKey: string | null
) => {
let url = `${
networkConfig[network!].blastUrl
}/builder/getWalletNFTs?contractAddress=${goldenTokenAddress}&walletAddress=${owner}&pageSize=100`;
if (nextPageKey) {
url += `&pageKey=${nextPageKey}`;
}
try {
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
const data = await response.json();
goldenTokens = goldenTokens.concat(
data?.nfts?.map((goldenToken: any) => {
const tokenId = JSON.parse(goldenToken.tokenId);
return Number(tokenId);
})
);
if (data.nextPageKey) {
return recursiveFetch(goldenTokens, data.nextPageKey);
}
} catch (ex) {
console.log("error fetching golden tokens", ex);
}
return goldenTokens;
};
const fetchAllPages = async (): Promise<number[]> => {
let goldenTokens: number[] = [];
let nextPageKey: string | null = null;
do {
let url = `${
networkConfig[network].blastUrl
}/builder/getWalletNFTs?contractAddress=${encodeURIComponent(goldenTokenAddress)}&walletAddress=${encodeURIComponent(owner)}&pageSize=100`;
if (nextPageKey) {
url += `&pageKey=${nextPageKey}`;
}
try {
const response = await fetch(url, {
method: "GET",
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
goldenTokens = goldenTokens.concat(
(data?.nfts ?? []).map((goldenToken: any) => {
const tokenId = Number(goldenToken.tokenId);
return tokenId;
})
);
nextPageKey = data.nextPageKey || null;
} catch (ex) {
console.log("error fetching golden tokens", ex);
break;
}
} while (nextPageKey);
return goldenTokens;
};
let goldenTokenData = await fetchAllPages();

Comment on lines +3 to +5
import BurnerLoader from "@/app/components/animations/BurnerLoader";
import Intro from "@/app/components/intro/Intro";
import LoginIntro from "@/app/components/onboarding/Intro";
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Clarify Component Naming to Avoid Confusion

The imports on lines 3-5 include both Intro and LoginIntro components:

import BurnerLoader from "@/app/components/animations/BurnerLoader";
import Intro from "@/app/components/intro/Intro";
import LoginIntro from "@/app/components/onboarding/Intro";

Having components with similar names can lead to confusion and maintainability issues. Consider renaming LoginIntro to a more descriptive name that reflects its specific purpose, or organizing them in a way that distinguishes their roles clearly.

import Head from "@/app/head";
import useUIStore from "@/app/hooks/useUIStore";
import { gameClient } from "@/app/lib/clients";
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Ensure lsGQLURL is Defined for All Networks

On line 12, the gameClient is imported:

import { gameClient } from "@/app/lib/clients";

Later, in the ApolloProvider, gameClient is called with:

<ApolloProvider client={gameClient(networkConfig[network].lsGQLURL!)}>

The exclamation mark ! asserts that lsGQLURL is not undefined. To prevent potential runtime errors, verify that lsGQLURL is defined for all possible values of network in networkConfig. If there's a chance that lsGQLURL could be undefined, include appropriate error handling or validation before using it.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f7a9072 and d79b900.

📒 Files selected for processing (1)
  • ui/src/app/api/getGoldenTokens.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (3)
ui/src/app/api/getGoldenTokens.ts (3)

1-9: LGTM: Function signature and imports are well-defined.

The function signature for getGoldenTokens is properly typed, and the necessary imports are present. This provides a good foundation for the implementation.


50-53: Consider updating main function execution if refactored

The current implementation is correct for the recursive approach. However, if you refactor to an iterative approach as suggested earlier, update this section accordingly.


1-53: Summary of review for getGoldenTokens.ts

The getGoldenTokens function provides a solid foundation for fetching golden tokens, but several improvements can enhance its robustness and efficiency:

  1. Improve type safety by replacing any types with explicit types.
  2. Enhance error handling and add proper checks for undefined values.
  3. Implement URL encoding for query parameters to prevent injection attacks.
  4. Consider refactoring the recursive approach to an iterative one for better efficiency and to avoid potential stack overflow issues with large datasets.

Addressing these points will significantly improve the function's reliability and maintainability.

Comment on lines +32 to +48
const data = await response.json();
goldenTokens = goldenTokens.concat(
data?.nfts?.map((goldenToken: any) => {
const tokenId = JSON.parse(goldenToken.tokenId);
return Number(tokenId);
})
);

if (data.nextPageKey) {
return recursiveFetch(goldenTokens, data.nextPageKey);
}
} catch (ex) {
console.log("error fetching golden tokens", ex);
}

return goldenTokens;
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

Refactor data processing and pagination logic

  1. Add a check for data.nfts before mapping.
  2. Remove unnecessary JSON.parse.
  3. Consider refactoring to an iterative approach for better efficiency and to avoid potential stack overflow.

Apply this diff to address the immediate issues:

  const data = await response.json();
  goldenTokens = goldenTokens.concat(
-   data?.nfts?.map((goldenToken: any) => {
+   (data?.nfts ?? []).map((goldenToken: any) => {
-     const tokenId = JSON.parse(goldenToken.tokenId);
-     return Number(tokenId);
+     return Number(goldenToken.tokenId);
    })
  );

  if (data.nextPageKey) {
    return recursiveFetch(goldenTokens, data.nextPageKey);
  }

Consider refactoring the entire function to use an iterative approach:

const fetchAllPages = async (): Promise<number[]> => {
  let goldenTokens: number[] = [];
  let nextPageKey: string | null = null;
  do {
    // Construct URL (with proper encoding)
    try {
      // Fetch and process data
      // Update nextPageKey
    } catch (ex) {
      console.error("Error fetching golden tokens:", ex);
      break;
    }
  } while (nextPageKey);
  return goldenTokens;
};

Comment on lines +24 to +31
try {
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Improve error handling in the fetch request

  1. Add a response status check before parsing JSON.
  2. Enhance error handling to provide more context.

Apply this diff to improve error handling:

  try {
    const response = await fetch(url, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    });

+   if (!response.ok) {
+     throw new Error(`HTTP error! Status: ${response.status}`);
+   }

    const data = await response.json();
    // ... rest of the code
  } catch (ex) {
-   console.log("error fetching golden tokens", ex);
+   console.error("Error fetching golden tokens:", ex);
+   throw new Error(`Failed to fetch golden tokens: ${ex.message}`);
  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
try {
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
// ... rest of the code
} catch (ex) {
console.error("Error fetching golden tokens:", ex);
throw new Error(`Failed to fetch golden tokens: ${ex.message}`);
}

Comment on lines +10 to +22
const recursiveFetch: any = async (
goldenTokens: any[],
nextPageKey: string | null
) => {
let url = `${
networkConfig[network!].blastUrl
}/builder/getWalletNFTs?contractAddress=${goldenTokenAddress}&walletAddress=${indexAddress(
owner
).toLowerCase()}&pageSize=100`;

if (nextPageKey) {
url += `&pageKey=${nextPageKey}`;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Improve type safety and security in URL construction

  1. Replace any types with explicit types for better type safety.
  2. Add a runtime check for network instead of using non-null assertion.
  3. URL-encode query parameters to prevent injection attacks.

Apply this diff to address these issues:

- const recursiveFetch: any = async (
-   goldenTokens: any[],
+ const recursiveFetch = async (
+   goldenTokens: number[],
  nextPageKey: string | null
- ) => {
+ ): Promise<number[]> => {
+   if (!network) {
+     throw new Error("Network is not defined");
+   }
    let url = `${
-     networkConfig[network!].blastUrl
+     networkConfig[network].blastUrl
-   }/builder/getWalletNFTs?contractAddress=${goldenTokenAddress}&walletAddress=${indexAddress(
-     owner
-   ).toLowerCase()}&pageSize=100`;
+   }/builder/getWalletNFTs?contractAddress=${encodeURIComponent(goldenTokenAddress)}&walletAddress=${encodeURIComponent(indexAddress(owner).toLowerCase())}&pageSize=100`;

    if (nextPageKey) {
-     url += `&pageKey=${nextPageKey}`;
+     url += `&pageKey=${encodeURIComponent(nextPageKey)}`;
    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const recursiveFetch: any = async (
goldenTokens: any[],
nextPageKey: string | null
) => {
let url = `${
networkConfig[network!].blastUrl
}/builder/getWalletNFTs?contractAddress=${goldenTokenAddress}&walletAddress=${indexAddress(
owner
).toLowerCase()}&pageSize=100`;
if (nextPageKey) {
url += `&pageKey=${nextPageKey}`;
}
const recursiveFetch = async (
goldenTokens: number[],
nextPageKey: string | null
): Promise<number[]> => {
if (!network) {
throw new Error("Network is not defined");
}
let url = `${
networkConfig[network].blastUrl
}/builder/getWalletNFTs?contractAddress=${encodeURIComponent(goldenTokenAddress)}&walletAddress=${encodeURIComponent(indexAddress(owner).toLowerCase())}&pageSize=100`;
if (nextPageKey) {
url += `&pageKey=${encodeURIComponent(nextPageKey)}`;
}

@starknetdev starknetdev merged commit b908030 into main Oct 7, 2024
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant